package make.free.app.mcaro.activity;

import java.io.IOException;

import make.free.app.mcaro.R;
import make.free.app.mcaro.Dialog.Dialog_Choice_Player;
import make.free.app.mcaro.bluetooth.BluetoothChatService;
import make.free.app.mcaro.bluetooth.DeviceListActivity;
import make.free.app.mcaro.game.Change;
import make.free.app.mcaro.game.Chat;
import make.free.app.mcaro.game.EventTitle;
import make.free.app.mcaro.game.MT;
import make.free.app.mcaro.game.O;
import make.free.app.mcaro.game.ProcessBar;
import make.free.app.mcaro.game.X;
import make.free.app.mcaro.util.Constan;

import org.anddev.andengine.audio.sound.Sound;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.SmoothCamera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class Game extends BaseGameActivity {
	public SmoothCamera mSmoothCamera;
	private Scene mScene;
	private Engine mEngine;
	public static Game game;
	private Context mContext;
	private ProcessBar mProgressBar;
	private Chat mChat;
	private Change mLuot;
	public static boolean isX = false;
	public static boolean isGameAI = false;
	float centx;
	float centy;
	public int value;
	public MT mt;
	public Dialog_Choice_Player play;
	public static String playerwin = "";
	private BluetoothChatService mChatService = null;
	private BluetoothAdapter mBluetoothAdapter = null;
	public static ArrayAdapter<String> mConversationArrayAdapter;
	public static boolean isMaster = false;
	public static ProgressDialog progressDialog;
	public static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
	public static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
	public static final int REQUEST_ENABLE_BT = 3;
	public static boolean isChat = false;
	public static Sound soundGameWin, soundGameLose, soundMassage;

	// public static boolean isTurn=false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		progressDialog = new ProgressDialog(this);
		EventTitle.Win = false;
		EventTitle.isEqual = false;
		progressDialog.setMessage("Please watting player accept");
		mConversationArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.message);
		initdata();
		if (!isGameAI) {
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			if (mBluetoothAdapter == null) {
				Toast.makeText(this, "Bluetooth is not available",
						Toast.LENGTH_LONG).show();
				finish();
				return;
			}
		}

	}

	@Override
	public void onStart() {
		super.onStart();
		if (!isGameAI) {
			Log.e("BLUETOOTH", "++ ON START ++");
			if (!mBluetoothAdapter.isEnabled()) {
				Intent enableIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
				// Otherwise, setup the chat session
			} else {
				if (mChatService == null)
					mChatService = new BluetoothChatService(this, mHandler);

			}
		}
	}

	@Override
	public synchronized void onResume() {
		super.onResume();

		// Performing this check in onResume() covers the case in which BT was
		// not enabled during onStart(), so we were paused to enable it...
		// onResume() will be called when ACTION_REQUEST_ENABLE activity
		// returns.
		if (!isGameAI) {
			if (mChatService != null) {
				// Only if the state is STATE_NONE, do we know that we haven't
				// started already
				if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
					// Start the Bluetooth chat services
					mChatService.start();
				}

			}

		}
	}

	@Override
	public Engine onLoadEngine() {
		// TODO Auto-generated method stub

		Display defaultDisplay;
		game = this;
		mContext = this;

		defaultDisplay = getWindow().getWindowManager().getDefaultDisplay();
		int CAMERA_WIDTH = defaultDisplay.getWidth();
		int CAMERA_HIGHT = defaultDisplay.getHeight();
		this.mSmoothCamera = new SmoothCamera(0, 0, 480, 800, 150, 150, 1.0f);
		centx = mSmoothCamera.getCenterX();
		centy = mSmoothCamera.getCenterY();
		this.mEngine = new Engine(new EngineOptions(true,
				ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(
						CAMERA_WIDTH, CAMERA_HIGHT), this.mSmoothCamera)
				.setNeedsSound(true).setNeedsMusic(true));

		return mEngine;
	}

	@Override
	public void onLoadResources() {
		// TODO Auto-generated method stub
		SoundFactory.setAssetBasePath("soundeffect/");

		try {
			soundGameWin = SoundFactory.createSoundFromAsset(
					mEngine.getSoundManager(), this, "win.mp3");
			soundGameLose = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "close.mp3");
			soundMassage = SoundFactory.createSoundFromAsset(
					mEngine.getSoundManager(), this, "buzz.mp3");
		} catch (final IOException e) {
		}
	}

	@Override
	public Scene onLoadScene() {
		// TODO Auto-generated method stub
		mScene = new Scene();
		mScene.setBackground(new ColorBackground(0f, 0f, 0f));
		// bacground
		Rectangle rec = new Rectangle(2, 0, 796, 76);
		rec.setColor(2.36f, 1.71f, 0.38f);
		mScene.attachChild(rec);
		// proceess bar
		mProgressBar = new ProcessBar(mContext, mEngine, mScene, 240,
				mChatService);
		mProgressBar.onLoadResources();
		mProgressBar.onLoadScene();
		if (isGameAI)
			mProgressBar.start();
		// icon chat
		mChat = new Chat(mContext, mEngine, mScene, 480, mChatService);
		mChat.onLoadResources();
		mChat.onLoadScene();
		// Luot
		mLuot = new Change(mContext, mEngine, mScene, 2);
		mLuot.onLoadResource();
		mLuot.onLoadScence();

		mt = new MT(mEngine, mScene, this, 4, 80);
		mt.createData();
		mt.createMT();
		// zoom
		mScene.setOnSceneTouchListener(new IOnSceneTouchListener() {
			@Override
			public boolean onSceneTouchEvent(final Scene pScene,
					final TouchEvent pSceneTouchEvent) {
				switch (pSceneTouchEvent.getAction()) {
				case TouchEvent.ACTION_DOWN:
					mSmoothCamera.setCenter(pSceneTouchEvent.getX(),
							pSceneTouchEvent.getY());
					Game.this.mSmoothCamera.setZoomFactor(2.0f);
					break;
				case TouchEvent.ACTION_UP:
					mSmoothCamera.setCenter(centx, centy);
					Game.this.mSmoothCamera.setZoomFactor(1.0f);
					break;
				}
				return true;
			}
		});
		mScene.registerUpdateHandler(updatehandle);
		return mScene;
	}

	//
	@Override
	public void onLoadComplete() {
		// TODO Auto-generated method stub

	}

	public void crateX(int positionX, int positionY, int x, int y) {
		X danhX = new X(mScene, mEngine, mContext);
		danhX.onLoadResources();
		danhX.onLoadScene(positionX, positionY, x, y);
	}

	public void crateO(int positionX, int positionY, int x, int y) {
		O danhO = new O(mScene, mEngine, mContext);
		danhO.onLoadResources();
		danhO.onLoadScene(positionX, positionY, x, y);
	}

	IUpdateHandler updatehandle = new IUpdateHandler() {

		@Override
		public void reset() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onUpdate(float pSecondsElapsed) {
			// TODO Auto-generated method stub

			if (EventTitle.Win == true) {
				mProgressBar.setStop(true);
				mScene.unregisterUpdateHandler(updatehandle);
				if (isGameAI) {
					soundGameWin.play();
					if (EventTitle.PlayerWin == value) {
						playerwin = "Bạn";
					} else {
						playerwin = "Máy";
					}
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							showFinish(playerwin);
						}
					});
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Log.e("PLAY WIN", playerwin);
							reStart();
							if (playerwin.equals("lose")) {
								soundGameLose.play();
								showWinLose("GAME OVER", "Bạn đã thua");
							} else if (playerwin.equals("win")) {
								soundGameWin.play();
								showWinLose("Chúc mừng!", "Bạn chiến thắng");
							} else if (EventTitle.PlayerWin == value) {
								soundGameWin.play();
								showWinLose("Chúc mừng!", "Bạn chiến thắng");
							} else {
								soundGameLose.play();
								showWinLose("GAME OVER", "Bạn đã thua");
							}
						}
					});
				}
			} else if (EventTitle.isEqual == true) {
				showWinLose("Hòa!", "Bạn và người chơi đã hòa nhau");
			} else {
				update();
			}
		}
	};

	public void showWinLose(String Title, String massage) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				mContext);

		// set title
		alertDialogBuilder.setTitle(Title);

		// set dialog message
		alertDialogBuilder
				.setMessage(massage)
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// if this button is clicked, just close
						// the dialog box and do nothing

						play = new Dialog_Choice_Player(mContext, mChatService);
						play.show();
						dialog.dismiss();
					}
				})
				.setNegativeButton("Menu",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// if this button is clicked, just close
								// the dialog box and do nothing
								dialog.dismiss();
								mScene.unregisterUpdateHandler(updatehandle);
								releaseMemory();
								mProgressBar.setStop(true);
								Game.this.finish();
							}
						});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();
	}

	public void showFinish(String playerwin) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				mContext);

		// set title
		alertDialogBuilder.setTitle("Kết quả");

		// set dialog message
		alertDialogBuilder
				.setMessage(playerwin + " " + "chiến thắng!!!")
				.setCancelable(false)
				.setPositiveButton("Chơi lại",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// if this button is clicked, close
								// current activity
								reStart();
								dialog.dismiss();

							}
						})
				.setNegativeButton("Menu",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// if this button is clicked, just close
								// the dialog box and do nothing
								mScene.unregisterUpdateHandler(updatehandle);
								releaseMemory();
								mProgressBar.setStop(true);
								Game.this.finish();
								dialog.dismiss();
							}
						});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();
	}

	public void releaseMemory() {
		BufferObjectManager.getActiveInstance().clear();
		getEngine().clearUpdateHandlers();
		getEngine().getScene().clearChildScene();
		getEngine().getScene().clearTouchAreas();
		// getEngine().getScene().clearUpdateHandlers();
		getEngine().getScene().clearEntityModifiers();
		getEngine().getFontManager().clear();

		System.gc();

	}

	public void reStart() {
		EventTitle.isEqual = false;
		EventTitle.Win = false;
		initdata();
		mt.createData();
		mt.createMT();
		if (isGameAI)
			mProgressBar.start();
		mScene.registerUpdateHandler(updatehandle);
	}

	public void update() {
		if (!isGameAI) {
			// Log.e("STATUSS", String.valueOf(mChatService.getState()));
			if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
				mScene.unregisterUpdateHandler(updatehandle);
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						mProgressBar.setStop(true);
						EventTitle.Win = false;
						initdata();
						mt.createData();
						mt.createMT();
						// mProgressBar.start();
						play = new Dialog_Choice_Player(mContext, mChatService);
						play.show();
					}
				});

			}
		}
		mLuot.updatePlay(EventTitle.player_change);
		if (isGameAI) {
			EventTitle.CheckAIPlay();
		}
		// ko phai ai thi dung lai
		if (!isGameAI) {
			if (EventTitle.player_change == 1) {
				mProgressBar.setPause(false);
			} else
				mProgressBar.setPause(true);
		}

	}

	private void initdata() {

		Bundle data = getIntent().getExtras();
		int isGameType = data.getInt("gametype");
		if (isGameType == 2)
			isGameAI = true;
		else
			isGameAI = false;
		// turn
		if (isGameAI) {

			// Chessman
			if (data.getInt("chessman") == 0) {
				value = 0;
				isX = true;

			} else {
				value = 1;
				isX = false;
			}
			int turn = data.getInt("turn");
			if (turn == 0)
				if (isX)
					EventTitle.player_change = 1;
				else
					EventTitle.player_change = 2;

			else {
				if (isX)
					EventTitle.player_change = 2;
				else
					EventTitle.player_change = 1;
			}

			if (EventTitle.player_change == 1) {
				EventTitle.reset();
			}
		}

	}

	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constan.MESSAGE_STATE_CHANGE:
				switch (msg.arg1) {
				case BluetoothChatService.STATE_CONNECTED:
					Log.e("STATE CONECT", "CONNECTED");
					mConversationArrayAdapter.clear();
					break;
				case BluetoothChatService.STATE_CONNECTING:
					Log.e("STATE CONECT", "CONNECTTING");
					break;
				case BluetoothChatService.STATE_LISTEN:
				case BluetoothChatService.STATE_NONE:
					Log.e("STATE NONE", "NOT CONNECT");
					break;
				}
				break;
			case Constan.MESSAGE_WRITE:
				byte[] writeBuf = (byte[]) msg.obj;
				// construct a string from the buffer
				String writeMessage = new String(writeBuf);
				// mConversationArrayAdapter.add("Me:  " + writeMessage);
				break;
			case Constan.MESSAGE_READ:
				byte[] readBuf = (byte[]) msg.obj;
				// construct a string from the valid bytes in the buffer
				String readMessage = new String(readBuf, 0, msg.arg1);
				Log.e("MESSAGE", readMessage);
				String[] parts = readMessage.split("-");
				Log.e("ID_MESSAGE", parts[0]);
				// message
				if (Integer.parseInt(parts[0]) == 0) {
					soundMassage.play();
					mConversationArrayAdapter.add("You" + ":  " + parts[1]);
					mConversationArrayAdapter.notifyDataSetChanged();
					isChat = true;
					if (isChat) {
						mChat.onchageICONOline();
						Dialog_Choice_Player.mChat
								.setBackgroundResource(R.drawable.chat_online);
					}
				} // get dieu kien
				else if (Integer.parseInt(parts[0]) == 1) {
					setupGame(parts[1] + "-" + parts[2]);
				} // chap nhan dieu kien
				else if (Integer.parseInt(parts[0]) == 2) {
					dismissProgressDialog();
					mProgressBar.start();
					play.cancel();

					// Chessman
					if (Dialog_Choice_Player.chessmanID == 0) {
						value = 0;
						isX = true;

					} else {
						value = 1;
						isX = false;
					}
					if (Dialog_Choice_Player.turnID == 0)
						if (isX)
							EventTitle.player_change = 1;
						else
							EventTitle.player_change = 2;

					else {
						if (isX)
							EventTitle.player_change = 2;
						else
							EventTitle.player_change = 1;
					}
					if (EventTitle.player_change == 1) {
						EventTitle.reset();
					}
				} // ko chap nhan
				else if (Integer.parseInt(parts[0]) == 3) {
					dismissProgressDialog();
					Toast.makeText(
							getApplicationContext(),
							"Người chơi không chấp nhận chọn quân cờ hoặc lượt chơi!",
							Toast.LENGTH_SHORT).show();
				}// danh quan co
				else if (Integer.parseInt(parts[0]) == 4) {
					EventTitle.CheckPlay2(Integer.parseInt(parts[1]),
							Integer.parseInt(parts[2]));
				}// bao hieu thang het thoi gian doi thu
				else if (Integer.parseInt(parts[0]) == 5) {
					EventTitle.Win = true;
					playerwin = "Chiến thắng";
				}
				break;
			case Constan.MESSAGE_DEVICE_NAME:
				// save the connected device's name
				dismissProgressDialog();
				String mConnectedDeviceName = msg.getData().getString(
						Constan.DEVICE_NAME);
				mScene.registerUpdateHandler(updatehandle);
				Toast.makeText(getApplicationContext(),
						"Đã được kết nối tới" + mConnectedDeviceName,
						Toast.LENGTH_SHORT).show();
				break;
			case Constan.MESSAGE_TOAST:
				Toast.makeText(getApplicationContext(),
						msg.getData().getString(Constan.TOAST),
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	public void sendMessage(String message) {
		// Check that we're actually connected before trying anything
		if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
			Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
					.show();
			return;
		}

		// Check that there's actually something to send
		if (message.length() > 0) {
			// Get the message bytes and tell the BluetoothChatService to write
			byte[] send = message.getBytes();
			mChatService.write(send);

			// Reset out string buffer to zero and clear the edit text field
			// mOutEditText.setText(mOutStringBuffer);
		}
	}

	private void connectDevice(Intent data, boolean secure) {
		// Get the device MAC address
		String address = data.getExtras().getString(
				DeviceListActivity.EXTRA_DEVICE_ADDRESS);
		// Get the BLuetoothDevice object
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		// Attempt to connect to the device
		mChatService.connect(device, secure);
	}

	public static void showProgressDialog() {
		try {
			if (progressDialog != null && progressDialog.isShowing() == false) {

				progressDialog.setCancelable(true);
				progressDialog.show();
			}
		} catch (Exception e) {
		}
	}

	public static void dismissProgressDialog() {
		try {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		} catch (Exception e) {
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// Stop the Bluetooth chat services
		if (mChatService != null)
			mChatService.stop();
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE_SECURE:
			// When DeviceListActivity returns with a device to connect
			if (resultCode == Activity.RESULT_OK) {
				Log.e("DATA", "" + data);
				connectDevice(data, true);
				showProgressDialog();
				// if (isMaster == true) {
				// mStart.setEnabled(true);
				// }
				// Log.e("Master", "" + isMaster);
			}
			break;
		case REQUEST_CONNECT_DEVICE_INSECURE:
			// When DeviceListActivity returns with a device to connect
			if (resultCode == Activity.RESULT_OK) {
				connectDevice(data, false);
			}
			break;
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled, so set up a chat session
				mChatService = new BluetoothChatService(this, mHandler);
			} else {
				// User did not enable Bluetooth or an error occured
				Log.d("BLUETOOTH", "BT not enabled");
				Toast.makeText(this, R.string.bt_not_enabled_leaving,
						Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}

	public void setupGame(String massage) {
		String[] parts = massage.split("-");
		int chessmanID = Integer.parseInt(parts[0]); //
		int turnID = Integer.parseInt(parts[1]); //
		Log.e("tu", "" + chessmanID);
		String massage1 = "", massage2 = "";
		if ((turnID == 0 && chessmanID == 0)
				|| (turnID == 1 && chessmanID == 1)) {
			turnID = 1;
		} else {
			turnID = 0;
		}

		if (chessmanID == 0) {
			massage1 = "Bạn sẽ chơi O -";
			chessmanID = 1;
		} else {
			massage1 = "Bạn sẽ chơi X -";
			chessmanID = 0;
		}

		if (turnID == 0) {
			massage2 = "Đánh trước";
		} else {
			massage2 = "Đánh sau";
		}

		String chuoi = massage1 + massage2;
		if (chuoi != null) {
			showFinish(chuoi, chessmanID, turnID);
		}

	}

	public void showFinish(String massage, final int chessmanID,
			final int turnID) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

		// set title
		alertDialogBuilder.setTitle("Hãy chấp nhận để thiết lập trò chơi");

		// set dialog message
		alertDialogBuilder
				.setMessage(massage)
				.setCancelable(false)
				.setPositiveButton("Chấp nhận",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								mProgressBar.start();
								sendMessage("2-3");

								// Chessman
								if (chessmanID == 0) {
									value = 0;
									isX = true;
								} else {
									value = 1;
									isX = false;
								}
								if (turnID == 0)
									EventTitle.player_change = 1;
								else {

									EventTitle.player_change = 2;
								}
								if (EventTitle.player_change == 1) {
									EventTitle.reset();
								}

								play.cancel();
								dialog.dismiss();
							}
						})
				.setNegativeButton("Hủy bỏ",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// if this button is clicked, just close
								// the dialog box and do nothing
								sendMessage("3-3");
								dialog.dismiss();
							}
						});
		;

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		mScene.unregisterUpdateHandler(updatehandle);
		releaseMemory();
		mProgressBar.setStop(true);
		if (!isGameAI)
			mChatService.stop();
		Game.this.finish();
	}
}
